from PyQt5.QtWidgets import QWidget
from PyQt5.QtGui import QPixmap, QImage, QPainter
from PyQt5.QtCore import Qt, QTimer
from PIL import Image


class WebpPlayer(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)

        # 设置透明背景
        self.setAttribute(Qt.WA_TranslucentBackground)
        self.setWindowFlags(Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint | Qt.SubWindow)

        # 动画相关变量
        self.frames = []  # 存储所有帧的QPixmap
        self.delays = []  # 每帧的延迟时间（毫秒）
        self.current_frame = 0
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.next_frame)
        
        # 调试用
        self.loaded = False

    def load_webp(self, file_path):
        """加载WebP动画文件"""
        try:
            self.frames.clear()
            self.delays.clear()
            self.current_frame = 0

            img = Image.open(file_path)

            # 如果是静态图片
            if not hasattr(img, 'n_frames'):
                qimage = self.pil_to_qimage(img)
                pixmap = QPixmap.fromImage(qimage)
                self.frames.append(pixmap)
                self.delays.append(100)
                self.loaded = True
                return True

            # 如果是动画
            for i in range(img.n_frames):
                img.seek(i)
                # 获取延迟时间（以毫秒为单位）
                delay = img.info.get('duration', 100)
                # 转换为QImage然后QPixmap
                qimage = self.pil_to_qimage(img)
                pixmap = QPixmap.fromImage(qimage)
                self.frames.append(pixmap)
                self.delays.append(delay)

            self.loaded = True
            return len(self.frames) > 0

        except Exception as e:
            print(f"加载WebP失败: {e}")
            self.loaded = False
            return False

    def pil_to_qimage(self, pil_image):
        """将PIL Image转换为QImage"""
        if pil_image.mode != 'RGBA':
            pil_image = pil_image.convert('RGBA')

        width, height = pil_image.size
        data = pil_image.tobytes("raw", "RGBA")
        qimage = QImage(data, width, height, QImage.Format_RGBA8888)
        return qimage

    def play(self):
        """播放动画"""
        if self.frames and self.loaded:
            self.timer.stop()
            self.current_frame = 0  # 重置到第一帧
            self.update()
            if len(self.frames) > 1:
                interval = self.delays[self.current_frame] if self.current_frame < len(self.delays) else 100
                self.timer.setInterval(interval)
                self.timer.start()

    def stop(self):
        """停止动画"""
        self.timer.stop()

    def next_frame(self):
        """切换到下一帧"""
        if self.frames and self.loaded:  # 确保有帧可显示
            old_frame = self.current_frame
            self.current_frame = (self.current_frame + 1) % len(self.frames)
            # 确保延迟数组索引有效
            if self.current_frame < len(self.delays):
                interval = self.delays[self.current_frame]
            else:
                interval = 100  # 默认值
            self.timer.setInterval(interval)
            self.update()

    def paintEvent(self, event):
        """绘制当前帧（居中显示）"""
        if not self.frames or not self.loaded:
            return

        painter = QPainter(self)
        painter.setRenderHint(QPainter.SmoothPixmapTransform)  # 抗锯齿

        # 获取当前帧
        current_pixmap = self.frames[self.current_frame]
        
        # 缩放图片保持宽高比
        scaled_pixmap = current_pixmap.scaled(
            self.size(),
            Qt.KeepAspectRatio,
            Qt.SmoothTransformation
        )

        # 居中显示
        x = (self.width() - scaled_pixmap.width()) // 2
        y = (self.height() - scaled_pixmap.height()) // 2

        painter.drawPixmap(x, y, scaled_pixmap)